package thread;

/**
 * @author lwmzzz
 * @version 1.0
 * @date 2021/1/26 22:40
 * @description 线程安全懒汉式
 */
public class BankTest {

}

/**
 * 线程不安全懒汉式
 */
class Bank {
    private Bank() {
    }

    private static Bank instance = null;

    public static Bank getInstance() {
        if (instance == null) {
            instance = new Bank();
        }
        return instance;
    }
}

/**
 * 饿汉式
 */
class HungryBank {
    private HungryBank() {
    }

    private static HungryBank instance = new HungryBank();


    public static HungryBank getInstance() {
        return instance;
    }
}

/**
 * 线程安全的懒汉式
 */
class SafeBank {
    private SafeBank() {
    }

    private static SafeBank instance = null;

    /**
     * 效率低
     *
     * @return
     */
    public static synchronized SafeBank getInstance() {
        if (instance == null) {
            instance = new SafeBank();
        }
        return instance;
    }

    /**
     * 效率高
     *
     * @return
     */
    public static SafeBank getInstance1() {
        if (instance == null) {
            synchronized (SafeBank.class) {
                if (instance == null) {
                    instance = new SafeBank();
                }
            }
        }
        return instance;
    }
}
